package com.nondo.dean.order.controller.api.admin;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nondo.dean.auth.common.annotation.HasRole;
import com.nondo.dean.auth.common.bean.RoleEnum;
import com.nondo.dean.common.annotation.ApiVersion;
import com.nondo.dean.common.tool.ValidateUtil;
import com.nondo.dean.common.web.Page;
import com.nondo.dean.common.web.Query;
import com.nondo.dean.common.web.View;
import com.nondo.dean.order.common.Constant;
import com.nondo.dean.order.common.OrderTip;
import com.nondo.dean.order.domain.OrderSubject;
import com.nondo.dean.order.model.param.OrderProductParam;
import com.nondo.dean.order.model.param.OrderStatusParam;
import com.nondo.dean.order.model.param.OrderSubjectSearchParam;
import com.nondo.dean.order.model.param.OrderTransmitParam;
import com.nondo.dean.order.model.param.PlatformOrderParam;
import com.nondo.dean.order.model.result.OrderSubjectResult;
import com.nondo.dean.order.model.result.OrderSubjectSearchResult;
import com.nondo.dean.order.service.OrderService;

/**
 * 订单管理后台接口
 *
 * @author zlj
 * @date 2018年4月18日
 */
@RestController("apiAdminOrder")
@RequestMapping("/{v}/admin/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    /**
     * 查看订单详情
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/info/{id}")
    public View<OrderSubject> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View<OrderSubject> view = new View<OrderSubject>(20000, "获取数据成功");

        OrderSubject order = null;
        if (id != null) {
            order = orderService.selectOrder(id);
        } else {
            order = new OrderSubject();
        }

        view.setData(order);
        return view;
    }

    /**
     * 平台代下单
     *
     * @param request
     * @param response
     * @param order    订单信息 {@link OrderSubject}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/add")
    public View<OrderSubject> createOrder(HttpServletRequest request, HttpServletResponse response,
                                  @Validated @RequestBody PlatformOrderParam orderParam, BindingResult result) {
        View<OrderSubject> view = new View<OrderSubject>(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            String message = PlatformOrderParam.checkInputParam(orderParam);
            if (message != null) {
                return View.ofParamsError(message);
            }
            this.orderService.createPlatformOrder(orderParam);
        }
        return view;
    }

    /**
     * 审核订单
     *
     * @param request
     * @param response
     * @param order    订单信息 {@link OrderSubject}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/audit")
    public View<OrderSubject> auditOrder(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @Validated @RequestBody OrderSubject order, BindingResult result) {
        View<OrderSubject> view = new View<OrderSubject>(20000, "审核成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            OrderSubject orderDb = this.orderService.selectOrder(order.getId());
            if(orderService.checkPermission(order) != 1){
                if(order.getAuditStatus().equals(Constant.HAVE_BEEN_AUDITED))
                    orderDb.setAuditStatus(Constant.HAVE_BEEN_AUDITED);
                if(order.getAuditStatus().equals(Constant.WATTING_TO_AUDITING))
                    orderDb.setAuditStatus(Constant.WATTING_TO_AUDITING);
                this.orderService.updateOrder(orderDb);
            }else{
                view.setMessage(OrderTip.YOU_NOT_PERMISSIONS);
                view.setCode(View.STATE_NOT_AUTH);
            }
        }

        return view;
    }

    /**
     * 获取订单分页查询列表
     *
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/list")
    public View<Page<OrderSubject>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<OrderSubject> query) {
        View<Page<OrderSubject>> view = new View<Page<OrderSubject>>(20000, "获取列表成功");

        OrderSubject order = query.getData();

        Page<OrderSubject> page = new Page<OrderSubject>(query.getPage(), query.getSize(), orderService.count(order));

        List<OrderSubject> orderList = orderService.getOrderList(query.getOffset(), query.getLimit(), order);

        page.setContent(orderList);

        view.setData(page);

        return view;
    }

    /**
     * 删除订单
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @SuppressWarnings("rawtypes")
    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View view = new View(20000, "删除成功");

        OrderSubject order = orderService.selectOrder(id);
        order.setDelFlag(String.valueOf(1));
        this.orderService.updateOrder(order);

        return view;
    }

    /**
     * 订单筛选
     *
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/search/list")
    public View<Page<OrderSubjectSearchResult>> searchList(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<OrderSubjectSearchParam> query) {
        View<Page<OrderSubjectSearchResult>> view = new View<Page<OrderSubjectSearchResult>>(20000, "获取列表成功");

        OrderSubjectSearchParam order = query.getData();
        
        if (query.getSize()==null) {
            query.setSize(10);
        }

        Page<OrderSubjectSearchResult> page = new Page<OrderSubjectSearchResult>(query.getPage(), query.getSize(), orderService.searchListCount(order));

        List<OrderSubjectSearchResult> orderList = orderService.searchList(query.getOffset(), query.getLimit(), order);

        page.setContent(orderList);

        view.setData(page);

        return view;
    }

    /**
     * 查看订单详情页面
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/view/{id}")
    public View<OrderSubjectResult> viewOrderDetails(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View<OrderSubjectResult> view = new View<OrderSubjectResult>(20000, "获取列表成功");
        OrderSubjectResult orderSubjectResult = null;
        if (id != null) {
            orderSubjectResult = orderService.searchOrderdetail(id);
        } else {
            orderSubjectResult = new OrderSubjectResult();
        }
        view.setData(orderSubjectResult);
        return view;
    }


    /**
     * 更新订单金额
     *
     * @param request
     * @param response
     * @param order
     * @return
     */
    @ApiVersion(1)
    @HasRole(RoleEnum.ADMIN)
    @RequestMapping("/update/amount")
    public View<String> updateOrderAmount(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @Validated @RequestBody OrderSubject order, BindingResult result) {
        View<String> view = new View<String>(20000, "更新成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            if(orderService.checkPermission(order) == 1){
                this.orderService.updateAmount(order);
            }else{
                view.setMessage(OrderTip.YOU_NOT_PERMISSIONS);
                view.setCode(View.STATE_ERROR);
            }

        }
        return view;
    }
    
    /**
     * 修改订单产品金额
     *
     * @param request
     * @param response
     * @param order    订单信息 {@link OrderProductParam}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/update")
    public View<OrderSubject> updateOrderProductPrice(HttpServletRequest request, HttpServletResponse response,
                                  @Validated @RequestBody OrderProductParam orderProductParam, BindingResult result) {
        View<OrderSubject> view = new View<OrderSubject>(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            String message = OrderProductParam.checkInputParam(orderProductParam);
            if (message != null) {
                return View.ofParamsError(message);
            }
            this.orderService.updateOrderProductPrice(orderProductParam);
        }
        return view;
    }

    /**
     * 订单状态跟踪
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/search/order/status")
    public View getOrderStatus(HttpServletRequest request,
                               HttpServletResponse response,@RequestBody OrderStatusParam param){

        return orderService.searchOrderStatus(param);
    }

    /**
     * 取消订单
     *
     * @param request
     * @param response
     * @param order    订单信息 {@link OrderSubject}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/cancel")
    public View<OrderSubject> cancelOrder(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @Validated @RequestBody OrderSubject order, BindingResult result) {
        View<OrderSubject> view = new View<OrderSubject>(20000, "取消成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            OrderSubject orderDb = this.orderService.selectOrder(order.getId());
            this.orderService.cancelOrder(orderDb);
        }

        return view;
    }

    /**
     * 订单同步
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/syn/order")
    public View synOrder(HttpServletRequest request,
                               HttpServletResponse response,@RequestBody OrderTransmitParam param){
        View<Map<String,String>> view = new View<Map<String,String>>(20000, "传输成功");

        Map<String,String> maps = orderService.orderToSap(param);
        if(maps.get("MSG_ERR") !=null && !"".equals(maps.get("MSG_ERR").toString())){
            view.setCode(50000);
            view.setMessage("传输失败");
        }else if(maps.get("RIGHT") !=null && !"".equals(maps.get("RIGHT").toString())){
            view.setCode(20000);
            view.setMessage("传输成功");
        }
        view.setData(maps);
        return view;
    }
}